
from odoo.http import request
from odoo.service import security

from odoo import registry as registry_get
from odoo import api, SUPERUSER_ID

from .api2 import SUPER_COMPANY_ID, DEMO_COMPANY_ID

# 前端登录后,
# comapny_id = 1 为平台公司
# comapny_id = 2 为demo公司, 需要创建数据库时, 首先创建, 确保 id =2
# allowed_companies 包含三家公司, [平台, demo, 自己的公司]
# current_company 为 [demo, 自己的公司] 之一
# 前端请求时, 设置 allowed_companies  = [current_company]
# 这样确保 前端只显示一家公司
# 前端 自己切换 current_company, 候选为 [demo, 自己的公司]
# 切换之后, 需要更新 session info


def _session_authenticate(db, login, uid):
    self = request.session
    # self.rotate = True
    self.rotate = False
    self.db = db
    self.uid = uid
    self.login = login
    self.session_token = uid and security.compute_session_token(
        self, request.env)
    request.uid = uid
    request.disable_db = False
    self.get_context()


def _auth_login(db, field, value):
    registry = registry_get(db)
    context = {}

    with registry.cursor() as cr:
        env = api.Environment(cr, SUPERUSER_ID, context)
        User = env['res.users']
        user = User.search([(field, '=', value)], limit=1)
        if not user:
            return None

        _session_authenticate(db, user.login, user.id)
        user = user.with_user(user)
        user._update_last_login()

    session_info = request.env['ir.http'].session_info()
    return _patch_session_info(session_info)


def _patch_session_info(session_info):

    csrf_token = request.csrf_token()
    info2 = dict(session_info, **{
        'csrf_token': csrf_token
    })

    # for odoo 13, session_id is not in session_info
    if not session_info.get('session_id'):
        info2 = dict(info2, **{
            'session_id': request.session.sid
        })

    # 补充 demo 公司  和 自己的 公司
    # user_companies': {
    # 'current_company': (2, 'Comp1'),
    # 'allowed_companies': [(2, 'Comp1'), (1, 'My Company')]}

    def find_comp(cid=None):
        user_companies = session_info['user_companies']
        allowed_companies = user_companies['allowed_companies']

        cs = [(rid, cname) for rid, cname in allowed_companies
              if (cid and [rid == cid] or [
                  rid not in (SUPER_COMPANY_ID, DEMO_COMPANY_ID)])[0]]

        return cs and cs[0] or None

    company_info = {
        'super_company_id': find_comp(SUPER_COMPANY_ID),
        'demo_company_id': find_comp(DEMO_COMPANY_ID),
        'me_company_id': find_comp(),
    }

    info2 = dict(info2, **{
        'company_info': company_info
    })

    print('xxxxxx, session_info,', info2)

    return info2
